package cn.ug.mall.service.impl;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.RateKeyEnum;
import cn.ug.mall.bean.*;
import cn.ug.mall.mapper.PrivilegeTemplateMapper;
import cn.ug.mall.mapper.RateSettingsMapper;
import cn.ug.mall.mapper.entity.*;
import cn.ug.mall.service.RateSettingsService;
import cn.ug.mall.web.submit.RateSettingSubmit;
import cn.ug.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 费率参数设置
 *
 * @author zhaohg
 * @date 2018/07/06.
 */
@Service
public class RateSettingsServiceImpl extends BaseServiceImpl implements RateSettingsService {

    @Autowired
    private RateSettingsMapper settingsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PrivilegeTemplateMapper privilegeTemplateMapper;

    @Override
    public SerializeObject operate(String keyName, RateSettingSubmit bean) {

        int success = 0;
        if (RateKeyEnum.BUY_GOLD.getKey().equals(keyName) || RateKeyEnum.SELL_GOLD.getKey().equals(keyName)
                || RateKeyEnum.RECHARGE.getKey().equals(keyName) || RateKeyEnum.WITHDRAW.getKey().equals(keyName)) {
            success = wrap(keyName, bean);
        }

        if (RateKeyEnum.LOGIN_PASSWORD.getKey().equals(keyName) || RateKeyEnum.TRADE_PASSWORD.getKey().equals(keyName)) {
            success = wrapPassword(keyName, bean);
        }

        if (RateKeyEnum.TAKE_GOLD.getKey().equals(keyName)) {
            success = takeGold(keyName, bean);
        }

        if (RateKeyEnum.IN_GOLD.getKey().equals(keyName)) {
            success = inGold(keyName, bean);
        }

        if (RateKeyEnum.FREIGHT.getKey().equals(keyName)) {
            success = freight(keyName, bean);
        }

        if (RateKeyEnum.BUY_SELL_GRAM.getKey().equals(keyName)) {
            if (bean.getBuyMaxGramPerDay() == null || bean.getBuyMaxGramPerDay() < 0 ||
                    bean.getSellMaxGramPerDay() == null || bean.getSellMaxGramPerDay() < 0) {
                return new SerializeObject<>(ResultType.ERROR, "00000002");
            }
            success = buySellGram(keyName, bean);
        }

        if (RateKeyEnum.UNPAID_TIME.getKey().equals(keyName)) {
            success = unpaidTime(keyName, bean);
        }
        /**金豆**/
        if (RateKeyEnum.GOLD_BEAN.getKey().equals(keyName)) {
            if (bean == null || bean.getGoldBean() == null) {
                return new SerializeObjectError("00000002");
            }
            GoldBean goldBean = JSON.parseObject(bean.getGoldBean(), GoldBean.class);
            checkParams(goldBean);
            success = goldBean(keyName, goldBean);
        }

        /**实物金**/
        if (RateKeyEnum.ENTITY_GOLD.getKey().equals(keyName)) {
            if (bean == null || bean.getEntityGoldSubmit() == null) {
                return new SerializeObjectError("00000002");
            }
            EntityGoldBean entityGoldSubmit = JSON.parseObject(bean.getEntityGoldSubmit(), EntityGoldBean.class);
            Ensure.that(entityGoldSubmit.getLeaseCloseType()).isNull("20300217");
            Ensure.that(entityGoldSubmit.getLeaseCalculateGoldType()).isNull("20300219");
            Ensure.that(entityGoldSubmit.getLeaseCalculateGoldType() == 2 && StringUtils.isBlank(entityGoldSubmit.getLeaseCalculateGoldTime())).isTrue("20300218");
            Ensure.that(entityGoldSubmit.getSpecificationList() == null || entityGoldSubmit.getSpecificationList().size() < 1).isTrue("20300220");
            Ensure.that(entityGoldSubmit.getSpecificationList() != null && entityGoldSubmit.getSpecificationList().size() > 10).isTrue("20300221");
            Ensure.that(entityGoldSubmit.getLeaseDayList() == null || entityGoldSubmit.getLeaseDayList().size() < 1).isTrue("20300222");
            Ensure.that(entityGoldSubmit.getLeaseDayList() != null && entityGoldSubmit.getLeaseDayList().size() > 10).isTrue("20300223");
            success = entityGold(keyName, entityGoldSubmit);
        }

        /**
         * 体验金
         */
        if (RateKeyEnum.EXPERIENCE_GOLD.getKey().equals(keyName)) {
            Ensure.that(bean.getCloseType()).isNull("20300217");
            Ensure.that(bean.getLeaseDayList() == null || bean.getLeaseDayList().size() < 1).isTrue("20300222");
            Ensure.that(bean.getLeaseDayList() != null && bean.getLeaseDayList().size() > 10).isTrue("20300223");
            success = experienceGold(keyName, bean);
        }

        /**
         * 买金优惠
         */
        if (RateKeyEnum.BUY_GOLD_PRIVILEGE.getKey().equals(keyName)) {
            GoldPrivilegeBean goldPrivilegeBean = JSON.parseObject(bean.getGoldPrivilegeBean(), GoldPrivilegeBean.class);
            Ensure.that(goldPrivilegeBean.getType()).isNull("20300226");
            Ensure.that(goldPrivilegeBean.getType() == 2 && goldPrivilegeBean.getPrivilegeType() == null).isTrue("20300227");
            Ensure.that(goldPrivilegeBean.getPrivilegeType() != null && goldPrivilegeBean.getSelectType() == null).isTrue("20300228");
            if (goldPrivilegeBean.getType() == 2) {

                if (goldPrivilegeBean.getPrivilegeType() == 1) {
                    if (goldPrivilegeBean.getSelectType() == 1) {
                        Ensure.that(goldPrivilegeBean.getFirstGramPrivilegeMoney() == null).isTrue("20300230");
                    } else if (goldPrivilegeBean.getSelectType() == 2) {
                        Ensure.that(goldPrivilegeBean.getFirstGramSecPrivilegeMoney() == null).isTrue("20300230");
                        Ensure.that(goldPrivilegeBean.getFirstGramNextPrivilegeMoney() == null).isTrue("20300231");
                        Ensure.that(goldPrivilegeBean.getFirstGramNextPrivilegeMoney().compareTo(BigDecimal.ZERO) <= 0).isTrue("20300231");
                    }
                }

                if (goldPrivilegeBean.getPrivilegeType() == 2) {
                    if (goldPrivilegeBean.getSelectType() == 1) {
                        Ensure.that(goldPrivilegeBean.getFirstGramPrivilegeBean() == null).isTrue("20300230");
                    } else if (goldPrivilegeBean.getSelectType() == 2) {
                        Ensure.that(goldPrivilegeBean.getFirstGramSecPrivilegeBean() == null).isTrue("20300230");
                        Ensure.that(goldPrivilegeBean.getFirstGramNextPrivilegeBean() == null).isTrue("20300231");
                        Ensure.that(goldPrivilegeBean.getFirstGramNextPrivilegeBean() <= 0).isTrue("20300231");
                    }
                }
                Ensure.that(goldPrivilegeBean.getSelectType() == 2 && (goldPrivilegeBean.getMaxPrivilegeGram() == null || goldPrivilegeBean.getMaxPrivilegeGram() > 40)).isTrue("20300232");

            }
            success = buyGoldPrivilege(keyName, goldPrivilegeBean);
        }

        /**
         * 金豆发放基础设置
         */
        if (RateKeyEnum.GOLD_BEAN_PROVIDE.getKey().equals(keyName)) {
            if (bean == null || bean.getGoldBeanProvide() == null) {
                return new SerializeObjectError("00000002");
            }
            GoldBeanProvide goldBeanProvide = JSON.parseObject(bean.getGoldBeanProvide(), GoldBeanProvide.class);
            checkParams(goldBeanProvide);
            success = goldBeanProvide(keyName, goldBeanProvide);
        }

        //金豆发放营销设置
        if (RateKeyEnum.GOLD_BEAN_PROVIDE_MARKET.getKey().equals(keyName)) {
            if (bean == null || bean.getGoldBeanProvideMarket() == null) {
                return new SerializeObjectError("00000002");
            }
            GoldBeanProvideMarket goldBeanProvideMarket = JSON.parseObject(bean.getGoldBeanProvideMarket(), GoldBeanProvideMarket.class);
            checkParams(goldBeanProvideMarket);
            success = goldBeanProvideMarket(keyName, goldBeanProvideMarket);
        }

        //对公转账账户设置
        if (RateKeyEnum.BROUGHT_TO_ACCOUNT.getKey().equals(keyName)) {
            if (bean == null || bean.getBroughtToAccount() == null) {
                return new SerializeObjectError("00000002");
            }
            BroughtToAccountBean broughtToAccountBean = JSON.parseObject(bean.getBroughtToAccount(), BroughtToAccountBean.class);
            checkParams(broughtToAccountBean);
            success = saveBroughtToAccount(keyName, broughtToAccountBean);
        }

        //折扣金
        if (RateKeyEnum.DISCOUNT_GOLD.getKey().equals(keyName)) {
            if (bean == null || bean.getDiscountGold() == null) {
                return new SerializeObjectError("00000002");
            }
            DiscountGoldBean discountGoldBean = JSON.parseObject(bean.getDiscountGold(), DiscountGoldBean.class);
            checkParams(discountGoldBean);
            success = saveDiscountGold(keyName, discountGoldBean);
        }

        if (success > 0) {
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }


    private int freight(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("fee", bean.getFee());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int wrap(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("minAmount", bean.getMinAmount());
        map.put("doneTime", bean.getDoneTime());
        map.put("isFee", bean.getIsFee());
        map.put("feeWay", bean.getFeeWay());
        map.put("feePeriod", bean.getFeePeriod());
        map.put("beforeNum", bean.getBeforeNum());
        map.put("beforeAmount", bean.getBeforeAmount());
        map.put("afterAmount", bean.getAfterAmount());
        map.put("hasDiscount", bean.getHasDiscount());
        map.put("discount", bean.getDiscount());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int wrapPassword(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("isLimited", bean.getIsLimited());
        map.put("wrongTimes", bean.getWrongTimes());
        map.put("minutes", bean.getMinutes());
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int takeGold(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("takeMaxGram", bean.getTakeMaxGram());
        map.put("takeIsDiscount", bean.getTakeIsDiscount());
        map.put("takeDiscount", bean.getTakeDiscount());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int inGold(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("inMaxGram", bean.getInMaxGram());
        map.put("inIsDiscount", bean.getInIsDiscount());
        map.put("inDiscount", bean.getInDiscount());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int buySellGram(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("buyMaxGramPerDay", bean.getBuyMaxGramPerDay());
        map.put("sellMaxGramPerDay", bean.getSellMaxGramPerDay());
        map.put("buyMaxGramStatus", bean.getBuyMaxGramStatus());
        map.put("sellMaxGramStatus", bean.getSellMaxGramStatus());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int unpaidTime(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("unpaidTime", bean.getUnpaidTime());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    /**
     * 金豆参数保存修改
     *
     * @param keyName
     * @param bean
     * @return
     */
    private int goldBean(String keyName, GoldBean bean) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(bean));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    /**
     * 金豆发放参数设置
     *
     * @param keyName
     * @param goldBeanProvide
     * @return
     */
    private int goldBeanProvide(String keyName, GoldBeanProvide goldBeanProvide) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(goldBeanProvide));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    /**
     * 金豆发放参数设置
     *
     * @param keyName
     * @param goldBeanProvideMarket
     * @return
     */
    private int goldBeanProvideMarket(String keyName, GoldBeanProvideMarket goldBeanProvideMarket) {
        //签到启用  签到类型1:每日签到金豆不同
        if (goldBeanProvideMarket.getSignStatus() == 1 && goldBeanProvideMarket.getSignType() == 1) {
            //前6天签到总和
            if (goldBeanProvideMarket.getSignFullType() == 1) {
                goldBeanProvideMarket.getSignDaysToGoldBeanList().remove(6);
                int goldBeanSum = goldBeanProvideMarket.getSignDaysToGoldBeanList().stream().mapToInt(o -> o).sum();
                goldBeanProvideMarket.getSignDaysToGoldBeanList().add(goldBeanSum);
            } else {
                //自定义金豆数
                //goldBeanProvideMarket.getSignDaysToGoldBeanList().add(goldBeanProvideMarket.getSignFullGoldBeanNum());
                goldBeanProvideMarket.setSignFullGoldBeanNum(goldBeanProvideMarket.getSignDaysToGoldBeanList().get(6));
            }
        }

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(goldBeanProvideMarket));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int saveBroughtToAccount(String keyName, BroughtToAccountBean broughtToAccountBean) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(broughtToAccountBean));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }


    private int entityGold(String keyName, EntityGoldBean entityGoldSubmit) {
        entityGoldSubmit.setSpecificationList(entityGoldSubmit.getSpecificationList().stream().sorted().collect(Collectors.toList()));
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(entityGoldSubmit));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int experienceGold(String keyName, RateSettingSubmit bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("closeType", bean.getCloseType());
        map.put("leaseDayList", bean.getLeaseDayList());

        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(map));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }


    private int buyGoldPrivilege(String keyName, GoldPrivilegeBean bean) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(bean));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    private int saveDiscountGold(String keyName, DiscountGoldBean discountGoldBean) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);
        RateSettingEntity entity = new RateSettingEntity();
        entity.setKeyName(keyName);
        entity.setKeyValue(JSONObject.toJSONString(discountGoldBean));

        if (rate == null) {
            return settingsMapper.insert(entity);
        }
        return settingsMapper.update(entity);
    }

    @Override
    public SerializeObject findByKeyName(String keyName, String accessToken) {
        RateSettingEntity rate = settingsMapper.findByKeyName(keyName);

        if (rate != null) {
            Map<String, Object> map = JSON.parseObject(rate.getKeyValue());
            //针对卖金多返回每人每日买卖克重限额字段  方便客户端查询
            if (RateKeyEnum.SELL_GOLD.getKey().equalsIgnoreCase(keyName)) {
                RateSettingEntity rateSettingEntity = settingsMapper.findByKeyName(RateKeyEnum.BUY_SELL_GRAM.getKey());
                Map<String, Object> parseObject = JSON.parseObject(rateSettingEntity.getKeyValue());
                map.putAll(parseObject);
            }

            if (org.apache.commons.lang3.StringUtils.isBlank(accessToken) &&
                    (RateKeyEnum.SELL_GOLD.getKey().equalsIgnoreCase(keyName) || RateKeyEnum.BUY_SELL_GRAM.getKey().equalsIgnoreCase(keyName))) {
                //每人每人限购克重是否启用  0不启用 1启用..
                if ("0".equals(String.valueOf(map.get("buyMaxGramStatus")))) {
                    map.put("buyMaxGramPerDay", 0);
                }
                //每人每人限卖克重是否启用  0不启用 1启用..
                if ("0".equals(String.valueOf(map.get("sellMaxGramStatus")))) {
                    map.put("sellMaxGramPerDay", 0);
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, map);
        }
        return new SerializeObject<>(ResultType.NORMAL, "没有数据");
    }

    @Override
    public SerializeObject save(PrivilegeTemplateBean privilegeTemplateBean) {
        //修改
        if (privilegeTemplateBean.getId() != null) {
            PrivilegeTemplateEntity privilegeTemplateEntity = privilegeTemplateMapper.findById(privilegeTemplateBean.getId());
            if (privilegeTemplateEntity == null) {
                return new SerializeObject<>(ResultType.NORMAL, "00000003");
            }
            Map map = new HashMap();
            map.put("schemeName", privilegeTemplateBean.getSchemeName());
            map.put("data", JSONObject.toJSONString(privilegeTemplateBean.getDataList()));
            map.put("id", privilegeTemplateBean.getId());
            int rows = privilegeTemplateMapper.update(map);
            Ensure.that(rows).isLt(1, "00000005");
        } else {
            //新增
            PrivilegeTemplateEntity privilegeTemplateEntity = new PrivilegeTemplateEntity();
            BeanUtils.copyProperties(privilegeTemplateBean, privilegeTemplateEntity);
            privilegeTemplateEntity.setData(JSONObject.toJSONString(privilegeTemplateBean.getDataList()));
            privilegeTemplateEntity.setStatus(2);
            privilegeTemplateEntity.setDeleted(1);
            int rows = privilegeTemplateMapper.insert(privilegeTemplateEntity);
            Ensure.that(rows).isLt(1, "00000005");
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject findTemplateByType(Integer type) {
        Map map = new HashMap();
        map.put("type", type);
        List<PrivilegeTemplateEntity> privilegeTemplateEntities = privilegeTemplateMapper.findList(map);

        if (!CollectionUtils.isEmpty(privilegeTemplateEntities)) {
            List<PrivilegeTemplateBean> privilegeTemplateBeans = new ArrayList<>();
            for (PrivilegeTemplateEntity templateEntity : privilegeTemplateEntities) {
                PrivilegeTemplateBean privilegeTemplateBean = new PrivilegeTemplateBean();
                BeanUtils.copyProperties(templateEntity, privilegeTemplateBean);
                List<TemplateBean> templateBeanList = JSONObject.parseArray(templateEntity.getData(), TemplateBean.class);
                privilegeTemplateBean.setDataList(templateBeanList);
                privilegeTemplateBeans.add(privilegeTemplateBean);
            }
            return new SerializeObject<>(ResultType.NORMAL, privilegeTemplateBeans);
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject findById(Integer id) {
        PrivilegeTemplateEntity privilegeTemplateEntity = privilegeTemplateMapper.findById(id);
        if (privilegeTemplateEntity == null) {
            return new SerializeObject<>(ResultType.NORMAL, "00000003");
        }
        PrivilegeTemplateBean privilegeTemplateBean = new PrivilegeTemplateBean();
        BeanUtils.copyProperties(privilegeTemplateEntity, privilegeTemplateBean);
        List<TemplateBean> templateBeanList = JSONObject.parseArray(privilegeTemplateEntity.getData(), TemplateBean.class);
        privilegeTemplateBean.setDataList(templateBeanList);
        return new SerializeObject<>(ResultType.NORMAL, privilegeTemplateBean);
    }

    @Override
    public SerializeObject delete(Integer id) {
        PrivilegeTemplateEntity privilegeTemplateEntity = privilegeTemplateMapper.findById(id);
        if (privilegeTemplateEntity == null) {
            return new SerializeObject<>(ResultType.NORMAL, "00000003");
        }
        Map map = new HashMap();
        map.put("id", id);
        map.put("deleted", 2);
        int rows = privilegeTemplateMapper.update(map);
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject templateSwitch(Integer id, Integer status) {
        PrivilegeTemplateEntity privilegeTemplateEntity = privilegeTemplateMapper.findById(id);
        if (privilegeTemplateEntity == null) {
            return new SerializeObject<>(ResultType.NORMAL, "00000003");
        }
        if (status == 1) {
            PrivilegeTemplateEntity templateEntity = privilegeTemplateMapper.findONTemplateByType(privilegeTemplateEntity.getType());
            if (templateEntity != null)
                return new SerializeObjectError("20300229");
        }
        Map map = new HashMap();
        map.put("id", id);
        map.put("status", status);
        int rows = privilegeTemplateMapper.update(map);
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject<PrivilegeTemplateBean> findONTemplateByType(Integer type) {
        PrivilegeTemplateEntity templateEntity = privilegeTemplateMapper.findONTemplateByType(type);
        PrivilegeTemplateBean privilegeTemplateBean = new PrivilegeTemplateBean();
        if (templateEntity != null) {
            BeanUtils.copyProperties(templateEntity, privilegeTemplateBean);
            List<TemplateBean> templateBeanList = JSONObject.parseArray(templateEntity.getData(), TemplateBean.class);
            privilegeTemplateBean.setDataList(templateBeanList);
            return new SerializeObject<>(ResultType.NORMAL, privilegeTemplateBean);
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject<List<String>> findShowVersions(String keyName) {
        List versions = new ArrayList();
        RateSettingEntity rateSettingEntity = settingsMapper.findByKeyName(keyName);
        if (rateSettingEntity != null) {
            Map<String, Object> parseObject = JSON.parseObject(rateSettingEntity.getKeyValue());
            versions = (List<String>)parseObject.get("appVersions");
        }
        return new SerializeObject<>(ResultType.NORMAL, versions);

    }

    /**
     * 修改显示/隐藏的版本
     *
     * @param keyName
     * @param showTag
     * @return
     */
    @Override
    public SerializeObject updateShowVesion(String keyName, Integer showTag ,List<String> versions) {
        RateSettingEntity rateSettingEntity = settingsMapper.findByKeyName(keyName);
        if (rateSettingEntity != null && showTag == 1) {
            List showVersions = new ArrayList();
            HashMap<String, Object> map = new HashMap<>();
            map.put("showTag", 1);
            map.put("appVersions", versions);

            RateSettingEntity entity = new RateSettingEntity();
            entity.setKeyName(keyName);
            entity.setKeyValue(JSONObject.toJSONString(map));
            int rows =  settingsMapper.update(entity);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObject<>(ResultType.ERROR, "00000002");
    }

    /**
     * 修改keyValue
     *
     * @param rateSettingEntity
     * @return
     */
    @Override
    public SerializeObject updateKeyValue(RateSettingEntity rateSettingEntity) {
        if (rateSettingEntity == null || StringUtils.isBlank(rateSettingEntity.getKeyValue())) {
            return new SerializeObject<>(ResultType.ERROR, "00000002");
        }
        RateSettingEntity rate = settingsMapper.findByKeyName(rateSettingEntity.getKeyValue());
        int rows = 0;
        if (rate == null) {
            rows =  settingsMapper.insert(rateSettingEntity);
        } else {
            rows =  settingsMapper.update(rateSettingEntity);
        }
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    /**
     * 修改品宣信息
     *
     * @param publicityInfoParamBean
     * @return
     */
    @Override
    public SerializeObject updatePublicityByParam(PublicityInfoParamBean publicityInfoParamBean) {
        HashMap<String, Object> map = new HashMap<>();
        RateSettingEntity entity = new RateSettingEntity();
        //关于我们
        entity.setKeyName(RateKeyEnum.ABOUT_US.getKey());
        map.put("showTag", publicityInfoParamBean.getAboutUsTag());
        entity.setKeyValue(JSONObject.toJSONString(map));
        int rows = 0;
        rows =  settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        //平台数据
        map.clear();
        entity.setKeyName(RateKeyEnum.PLATFORM_DATA.getKey());
        map.put("showTag", publicityInfoParamBean.getPlatformDataTag());
        map.put("inputGoldGram", publicityInfoParamBean.getInputGoldGram());
        map.put("inputServeUser", publicityInfoParamBean.getInputServeUser());
        entity.setKeyValue(JSONObject.toJSONString(map));
        rows =  settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        //客服作息时间
        map.clear();
        entity.setKeyName(RateKeyEnum.CUSTOMER_SERVICE_SCHEDULE.getKey());
        map.put("showTag", publicityInfoParamBean.getCustomerServiceScheduleTag());
        map.put("am", publicityInfoParamBean.getAmTime());
        map.put("pm", publicityInfoParamBean.getPmTime());
        entity.setKeyValue(JSONObject.toJSONString(map));
        rows = settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        //产品热销标签
        map.clear();
        entity.setKeyName(RateKeyEnum.HOT_PRODUCT_LABEL.getKey());
        List<String> physicalGoldLabels = new ArrayList<>();
        physicalGoldLabels.add(publicityInfoParamBean.getPhysicalGoldLabel1());
        physicalGoldLabels.add(publicityInfoParamBean.getPhysicalGoldLabel2());
        List<String> secureGoldLabels = new ArrayList<>();
        secureGoldLabels.add(publicityInfoParamBean.getSecureGoldLabel1());
        secureGoldLabels.add(publicityInfoParamBean.getSecureGoldLabel2());
        map.put("physicalGold", physicalGoldLabels);
        map.put("secureGold", secureGoldLabels);
        entity.setKeyValue(JSONObject.toJSONString(map));
        rows = settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    /**
     * 获取品宣模块配置信息
     *
     * @return
     */
    @Override
    public SerializeObject findPublicity() {
        PublicityInfoBean infoBean = new PublicityInfoBean();
        RateSettingEntity aboutUsEntity = settingsMapper.findByKeyName(RateKeyEnum.ABOUT_US.getKey());
        Map<String, Object> parseObject = JSON.parseObject(aboutUsEntity.getKeyValue());
        infoBean.setAboutUsTag((Integer)parseObject.get("showTag"));
        RateSettingEntity platformDataEntity = settingsMapper.findByKeyName(RateKeyEnum.PLATFORM_DATA.getKey());
        Map<String, Object> platformData = JSON.parseObject(platformDataEntity.getKeyValue());
        infoBean.setPlatformDataTag((Integer) platformData.get("showTag"));
        infoBean.setInputGoldGram((Integer) platformData.get("inputGoldGram"));
        infoBean.setInputServeUser((Integer) platformData.get("inputServeUser"));

        RateSettingEntity customerServiceScheduleEntity = settingsMapper.findByKeyName(RateKeyEnum.CUSTOMER_SERVICE_SCHEDULE.getKey());
        Map<String, Object> customerServiceSchedule = JSON.parseObject(customerServiceScheduleEntity.getKeyValue());
        infoBean.setCustomerServiceScheduleTag((Integer) customerServiceSchedule.get("showTag"));
        infoBean.setAmTime(customerServiceSchedule.get("am") + "");
        infoBean.setPmTime(customerServiceSchedule.get("pm") + "");

        RateSettingEntity hotProductLabelEntity = settingsMapper.findByKeyName(RateKeyEnum.HOT_PRODUCT_LABEL.getKey());
        Map<String, Object> hotProductLabel = JSON.parseObject(hotProductLabelEntity.getKeyValue());
        infoBean.setPhysicalGoldLabel1(((List<String>)hotProductLabel.get("physicalGold")).get(0));
        infoBean.setPhysicalGoldLabel2(((List<String>)hotProductLabel.get("physicalGold")).get(1));
        infoBean.setSecureGoldLabel1(((List<String>)hotProductLabel.get("secureGold")).get(0));
        infoBean.setSecureGoldLabel2(((List<String>)hotProductLabel.get("secureGold")).get(1));

        return new SerializeObject<>(ResultType.NORMAL, infoBean);
    }

    /**
     * 获取投资版块配置信息
     *
     * @return
     */
    @Override
    public SerializeObject findInvestArea() {
        InvestBoardBean investBoardBean = new InvestBoardBean();
        RateSettingEntity productShowEntity = settingsMapper.findByKeyName(RateKeyEnum.PRODUCT_SHOW_AREA.getKey());
        Map<String,Object> productShowValue = JSON.parseObject(productShowEntity.getKeyValue());
        investBoardBean.setModuleTitleList((List<ModuleTitle>) productShowValue.get("moduleTitles"));

        RateSettingEntity businessIntroductionAreaBean = settingsMapper.findByKeyName(RateKeyEnum.BUSINESS_INTRODUCTION_AREA.getKey());
        Map<String, Object> businessIntroValue = JSON.parseObject(businessIntroductionAreaBean.getKeyValue());
        investBoardBean.setBusinessShowTag((Integer) businessIntroValue.get("showTag"));
        investBoardBean.setBusinessIntroductions(JSON.parseArray(businessIntroValue.get("businessIntroductions")+"",BusinessIntroduction.class));

        RateSettingEntity investDynamicEntity = settingsMapper.findByKeyName(RateKeyEnum.INVEST_DYNAMIC.getKey());
        Map<String,Object> investDynamicValue = JSON.parseObject(investDynamicEntity.getKeyValue());
        investBoardBean.setInvestDynamicShowTag((Integer) investDynamicValue.get("showTag"));
        investBoardBean.setInvestReadNum((Integer) investDynamicValue.get("readNum"));

        return new SerializeObject<>(ResultType.NORMAL, investBoardBean);
    }

    @Override
    public SerializeObject updateInvestAreaByParam(InvestBoardParamBean paramBean) {
        HashMap<String, Object> map = new HashMap<>();
        RateSettingEntity entity = new RateSettingEntity();
        //产品展示区
        entity.setKeyName(RateKeyEnum.PRODUCT_SHOW_AREA.getKey());
        //map.put("productModule", paramBean.getModuleTitleList());
        ModuleTitleBean moduleTitleBean = new ModuleTitleBean();
        moduleTitleBean.setModuleTitles(paramBean.getModuleTitles());
        entity.setKeyValue(JSONObject.toJSONString(moduleTitleBean));
        int rows = 0;
        rows =  settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        //业务介绍区
        map.clear();
        entity.setKeyName(RateKeyEnum.BUSINESS_INTRODUCTION_AREA.getKey());
        BusinessIntroductionBean businessIntroductionBean = new BusinessIntroductionBean();
        businessIntroductionBean.setShowTag(paramBean.getBusinessShowTag());
        businessIntroductionBean.setBusinessIntroductions(paramBean.getIntroductions());
        entity.setKeyValue(JSONObject.toJSONString(businessIntroductionBean));
        rows =  settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        //投资动态
        map.clear();
        entity.setKeyName(RateKeyEnum.INVEST_DYNAMIC.getKey());
        map.put("showTag", paramBean.getInvestDynamicShowTag());
        map.put("readNum", paramBean.getInvestReadNum());
        entity.setKeyValue(JSONObject.toJSONString(map));
        rows = settingsMapper.update(entity);
        Ensure.that(rows).isLt(1, "00000005");
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject<List<ModuleTitle>> findProductModule() {
        List<ModuleTitle> list = new ArrayList<>();
        RateSettingEntity productShowEntity = settingsMapper.findByKeyName(RateKeyEnum.PRODUCT_SHOW_AREA.getKey());
        Map<String,Object> productShowValue = JSON.parseObject(productShowEntity.getKeyValue());
        if (null == productShowValue.get("moduleTitles")) {
            return new SerializeObject<>(ResultType.NORMAL, list);
        }
        try {
            list = (List<ModuleTitle>)productShowValue.get("moduleTitles");
        } catch (Exception e) {
            return new SerializeObject<>(ResultType.ERROR, "00000005");
        }
        return new SerializeObject<>(ResultType.NORMAL, list);
    }


    /**
     * 金豆基础设置参数校验
     *
     * @param goldBean
     */
    private void checkParams(GoldBean goldBean) {
        Ensure.that(goldBean.getGoldBeanNum()).isNull("20300224");
        Ensure.that(goldBean.getGoldGram()).isNull("20300225");
        Ensure.that(goldBean.getExpireType() == null).isTrue("20300233");
        Ensure.that(goldBean.getExpireType() == 1 && (StringUtils.isBlank(goldBean.getAbatementDate())
                || goldBean.getAbatementType() == null)).isTrue("20300234");
        Ensure.that(goldBean.getExchangeType() == null).isTrue("20300235");
        Ensure.that(goldBean.getExchangeType() == 1 && goldBean.getExchangeOrigin() == null).isTrue("20300236");
        Ensure.that(goldBean.getGoldBeanMin() == null).isTrue("20300237");
        Ensure.that(goldBean.getGoldBeanMax() == null).isTrue("20300238");
    }

    /**
     * 金豆发放基础设置参数校验
     *
     * @param goldBeanProvide
     */
    private void checkParams(GoldBeanProvide goldBeanProvide) {
        Ensure.that(goldBeanProvide.getRegisterGoldBean()).isNull("20300239");
        Ensure.that(goldBeanProvide.getTiedCardGoldBean()).isNull("20300240");
        Ensure.that(goldBeanProvide.getFirstBuyExperienceGold()).isNull("20300241");
        Ensure.that(goldBeanProvide.getFirstBuyEntityGold()).isNull("20300242");
        Ensure.that(goldBeanProvide.getFirstLeaseBack()).isNull("20300243");
        Ensure.that(goldBeanProvide.getFirstBuyGoldOrnament()).isNull("20300244");
    }

    /**
     * 金豆发放基础设置参数校验
     *
     * @param goldBeanProvideMarket
     */
    private void checkParams(GoldBeanProvideMarket goldBeanProvideMarket) {
        Ensure.that(goldBeanProvideMarket.getInviteFriendsStatus()).isNull("20300245");
        Ensure.that(goldBeanProvideMarket.getInviteFriendsStatus() == 1 && (goldBeanProvideMarket.getInviterGiveGoldBean() == null
                || goldBeanProvideMarket.getInviteeGiveGoldBean() == null)).isTrue("20300246");
        Ensure.that(goldBeanProvideMarket.getSignStatus()).isNull("20300247");

        if (goldBeanProvideMarket.getSignStatus() == 1) {
            Ensure.that(goldBeanProvideMarket.getSignType()).isNull("20300248");
            //1:每日签到金豆不同
            if (goldBeanProvideMarket.getSignType() == 1) {
                Ensure.that(CollectionUtils.isEmpty(goldBeanProvideMarket.getSignDaysToGoldBeanList())
                        || goldBeanProvideMarket.getSignDaysToGoldBeanList().size() < 6).isTrue("20300249");
                Ensure.that(goldBeanProvideMarket.getSignFullType()).isNull("20300250");
                //Ensure.that(goldBeanProvideMarket.getSignFullType()==2 && goldBeanProvideMarket.getSignFullGoldBeanNum() == null).isTrue("20300251");
            }

            //2.每日签到数相同
            if (goldBeanProvideMarket.getSignType() == 2) {
                Ensure.that(goldBeanProvideMarket.getGoldBeanNum()).isNull("20300249");
                Ensure.that(goldBeanProvideMarket.getSignFullGoldBeanNum() == null).isTrue("20300251");
            }
        }
    }

    /**
     * 对公账号参数校验
     *
     * @param broughtToAccountBean
     */
    private void checkParams(BroughtToAccountBean broughtToAccountBean) {
        //Ensure.that(StringUtils.isBlank(broughtToAccountBean.getAccountName())).isTrue("20300252");
        //Ensure.that(StringUtils.isBlank(broughtToAccountBean.getBankAccount())).isTrue("20300253");
        if (StringUtils.isNotBlank(broughtToAccountBean.getBankAccount())) {
            Ensure.that(broughtToAccountBean.getBankAccount().length() > 50).isTrue("20300254");
        }
        //Ensure.that(StringUtils.isBlank(broughtToAccountBean.getOpenBank())).isTrue("20300255");
        if (StringUtils.isNotBlank(broughtToAccountBean.getOpenBank())) {
            Ensure.that(broughtToAccountBean.getOpenBank().length() > 50).isTrue("20300256");
        }
    }

    private void checkParams(DiscountGoldBean discountGoldBean) {
        Ensure.that(discountGoldBean.getLeaseDayList() == null).isTrue("20300222");
        Ensure.that(discountGoldBean.getLeaseDayList().size() < 1).isTrue("20300222");
        Ensure.that(discountGoldBean.getLeaseDayList().size() > 10).isTrue("20300223");
    }

}
